package com.elite.groovy.callback


import com.elite.groovy.util.EliteBean;
import com.elite.groovy.util.Util;
import com.elite.groovy.kh.KHDBConfig
import com.alibaba.fastjson.JSONObject
import com.wisdge.dataservice.Result
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import com.elite.groovy.kh.KHUtil

/**
 * @projectName: ngsapi_cs
 * @package: cn.com.callback
 * @className: apiShortenLink
 * @author: LiJT
 * @description: 生成动态页面短链接的API
 * @date: 2022-12-19 14:03
 * @version: 1.0
 */

public class apiShortenLink implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiShortenLink.class);
    private static String in_DomainURL = "";

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);
        if (!getMethod.equals("GET")) {
            log.error("HTTP请求调用类型错误，接口调用失败：" + getMethod);
            return JSONObject.toJSONString(new Result(Result.ERROR, "HTTP请求调用类型错误，接口调用失败：" + getMethod));
        }

        // 获取数据源List<Map<String, Object>>
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        String out_DomainURL = KHDBConfig.getAPIURL(eliteBean, "SYS-OuterDomain");
        out_DomainURL = out_DomainURL.endsWith("/") ? out_DomainURL : out_DomainURL + "/";

        //获取所有参数名
        Enumeration e = request.getParameterNames();
        while (e.hasMoreElements()) {
            String parameterName = (String) e.nextElement();
            log.debug(parameterName + ": " + request.getParameter(parameterName));
        }

        String dynid = request.getParameter("dynid");
        String userid = request.getParameter("userid");
        String usertype = request.getParameter("usertype");
        String woid = request.getParameter("woid");
        String taskid = request.getParameter("taskid");
        String expand = request.getParameter("expand");
        String cbtype = request.getParameter("cbtype"); // 返回结果类型 json 或 redirect ,redirect将会直接重定向
        String opsource = request.getParameter("opsource");
        String type = request.getParameter("type");
        log.debug("原始Get请求参数-dynid:" + dynid + " userid:" + userid + " usertype:" + usertype + " woid:" + woid + " taskid:" + taskid + " expand:" + expand + " cbtype:" + cbtype + " opsource:" + opsource + " type:" + type);

        String checkNullInfo = KHUtil.isNullMSG("dynid", dynid) + KHUtil.isNullMSG("userid", userid);
        log.debug("非空校验检查结果:" + checkNullInfo);
        if (!KHUtil.isNull(checkNullInfo)) {
            if (cbtype.equals("redirect")) {
                response.sendRedirect(out_DomainURL + "ngs/404.html?ErrorTitle=" + URLEncoder.encode("页面异常", "UTF-8") + "&ErrorInfo=" + URLEncoder.encode("非空校验检查结果:" + checkNullInfo, "UTF-8").replaceAll("\\+", "%20"));
            } else {
                return JSONObject.toJSONString(new Result(Result.ERROR, checkNullInfo));
            }

        } else {

            try {

                in_DomainURL = KHDBConfig.getAPIURL(eliteBean, "SYS-InnerDomain");
                in_DomainURL = in_DomainURL.endsWith("/") ? in_DomainURL : in_DomainURL + "/";
                String url = in_DomainURL + "ngs/S";

                // 获取短码标准入参
                JSONObject content = new JSONObject();
                content.put("at", "dyn2");
                content.put("mt", "r");
                content.put("q", "sp");
                content.put("ai", dynid);

                // 客制化参数部分
                JSONObject requestParams = new JSONObject();
                requestParams.put("WOID", woid);
                requestParams.put("TASKID", taskid);
                requestParams.put("EXPAND", expand);
                requestParams.put("USERID", userid);
                requestParams.put("USERTYPE", usertype);
                requestParams.put("OPSOURCE", opsource);
                requestParams.put("TYPE", type);
                content.put("params", requestParams);

                // 封装调用参数
                JSONObject params = new JSONObject();
                params.put("ttl", 0);
                params.put("content", content.toJSONString());
                log.debug("封装调用参数params:" + params.toString());

                // 发起调用
                Map<String, String> headMap = new HashMap<String, String>();
                headMap.put("Content-Type", "application/json");

                String resultBody = Util.doHttpPostUseHead(url, params.toString(), "UTF-8", 5000, 0, headMap);
                log.debug("调用返回resultBody:" + resultBody);

                // 解析调用参数
                JSONObject resultJson = JSONObject.parseObject(resultBody);
                if (resultJson.getInteger("code") == 1) {
                    log.debug("调用NGS生成短码成功！" + resultJson.getString("value"));

                    if (cbtype.equals("redirect")) {
                        response.sendRedirect(out_DomainURL + "ngs/m/nl?" + resultJson.getString("value"));
                    } else {
                        return JSONObject.toJSONString(new Result(Result.SUCCESS, out_DomainURL + "ngs/m/nl?" + resultJson.getString("value")));
                    }
                } else {

                    log.warn("调用NGS生成短码错误！" + resultJson.getString("message"));

                    if (cbtype.equals("redirect")) {
                        response.sendRedirect(out_DomainURL + "ngs/404.html?ErrorTitle=" + URLEncoder.encode("页面异常", "UTF-8") + "&ErrorInfo=" + URLEncoder.encode("调用NGS生成短码错误！" + resultJson.getString("message"), "UTF-8").replaceAll("\\+", "%20"));

                    } else {
                        return JSONObject.toJSONString(new Result(Result.WARN, "调用NGS生成短码错误！", resultJson.getString("message")));
                    }
                }

            } catch (Exception e1) {
                log.error("调用NGS生成短码链接异常：", e1);

                if (cbtype.equals("redirect")) {
                    response.sendRedirect(out_DomainURL + "ngs/404.html?ErrorTitle=" + URLEncoder.encode("页面异常", "UTF-8") + "&ErrorInfo=" + URLEncoder.encode("调用NGS生成短码链接异常：" + e1.getMessage(), "UTF-8").replaceAll("\\+", "%20"));

                } else {
                    return JSONObject.toJSONString(new Result(Result.ERROR, "调用NGS生成短码链接异常：" + e1.getMessage()));
                }
            }
        }
    }
}
